import { ref, reactive } from 'vue'
import { getExamList } from '@/api/server/exam'
import { ElMessage } from 'element-plus'
import { useServerUserStore } from '@/stores/modules/user-server'

/**
 * 评阅任务查询Hook
 * @returns {Object} 包含查询相关的状态和方法
 */
export default function useReviewTaskQuery() {
  const userStore = useServerUserStore()

  // 加载状态
  const loading = ref(false)
  
  // 表格数据
  const examList = ref([])
  const timeOrder = ref('desc') // 默认时间降序
  const reviewStatus = ref('所有状态') // 默认全部批阅状态
  
  // 分页控制
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0) // 总记录数
  
  // 获取考试列表
  const fetchExams = async () => {
    loading.value = true
    try {
      const response = await getExamList({
        page: currentPage.value,
        pageSize: pageSize.value,
        timeOrder: timeOrder.value,
        reviewStatus: reviewStatus.value,
        userId: userStore.userInfo.id
      })
      
      
      // 处理接口返回的数据
      examList.value = response.data.data.list || []
      total.value = response.data.data.total || 0
      
      loading.value = false
      return { success: true, data: examList.value }
    } catch (error) {
      console.error('获取考试列表失败', error)
      ElMessage.error('获取考试列表失败')
      loading.value = false
      return { success: false, error }
    }
  }
  
  // 查询处理
  const handleQuery = async () => {
    currentPage.value = 1
    return await fetchExams()
  }
  
  // 重置查询条件
  const handleReset = async () => {
    timeOrder.value = 'desc'
    reviewStatus.value = '所有状态'
    currentPage.value = 1
    return await fetchExams()
  }
  
  // 分页处理
  const handleSizeChange = async (val) => {
    pageSize.value = val
    currentPage.value = 1
    return await fetchExams()
  }
  
  const handleCurrentChange = async (val) => {
    currentPage.value = val
    return await fetchExams()
  }
  
  // 格式化日期时间
  const formatDateTime = (cellValue) => {
    if (!cellValue) return ''
    const date = new Date(cellValue)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  }
  
  // 表格行样式
  const tableRowClassName = ({ row }) => {
    if (row.examinationStatus === '已批阅') {
      return 'success-row'
    }
    return ''
  }
  
  return {
    // 状态
    loading,
    examList,
    timeOrder,
    reviewStatus,
    currentPage,
    pageSize,
    total,
    
    // 方法
    fetchExams,
    handleQuery,
    handleReset,
    handleSizeChange,
    handleCurrentChange,
    formatDateTime,
    tableRowClassName
  }
} 